﻿using Growatt.OSC.Util;
using Growatt.WaveData.DataSetResolve;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vosc;
using Vosc.VirtualOscilloscope;

namespace Growatt.WaveData.VirtualOscilloscope
{

    /// <summary>
    /// 参数配置界面
    /// </summary>
    public partial class UC_ParameterSetting : UserControl
    {

        public enum Typemodel
        {
            U16,
            I16,
            F32,
        }
        public enum Scalemodel
        {
            x10,
            x100,
            x1k,
            x10k,
            x100k,
        }
        public string Address { get; set; }
        public int I { get; }


        private UIComboDataGridView uiComboDataGridView2 = new UIComboDataGridView()
        {
            DropDownWidth = 500,
            Font = new System.Drawing.Font("宋体", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)))
        };

        public void ChangetextBox1(string text)
        {
            try
            {
                if (!string.IsNullOrEmpty(uiComboDataGridView2.Text))
                {
                    VariableInfo variableInfo = new VariableInfo(uiComboDataGridView2.Text, string.Empty);
                    DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });

                    if (!string.IsNullOrEmpty(variableInfo.Address))
                    {
                        textBox1.Text = variableInfo.Address;
                    }
                    else
                    {
                        textBox1.Text = "0000000";
                    }
                }
                else
                {
                    textBox1.Text = "0000000";
                }
            }
            catch (Exception)
            {

            }
        }


        DataTable dt = new DataTable();

        UIDataGridView uIDataGridView = null;

        public Action<string> ShowParameter = null;
        public UC_ParameterSetting(int i)
        {
            InitializeComponent();
            this.Load += (_, u) =>
            {
                this.components = new System.ComponentModel.Container();
                UIStyleManager StyleManager = new Sunny.UI.UIStyleManager(this.components);
                UIStyle style = (UIStyle)101;
                if (style != UIStyle.Colorful)
                    StyleManager.Style = style;
            };
            uiComboDataGridView2.DataGridView.Init();
            uiComboDataGridView2.DataGridView.MultiSelect = true;//设置可多选
            uiComboDataGridView2.ItemSize = new System.Drawing.Size(500, 200);
            uiComboDataGridView2.DataGridView.AddColumn("参数名称", "Name");
            uiComboDataGridView2.DataGridView.AddColumn("类型", "Type", fillWeight: 30);
            uiComboDataGridView2.DataGridView.AddColumn("倍率", "Scale", fillWeight: 30);
            uiComboDataGridView2.DataGridView.AddColumn("地址", "Address", fillWeight: 30);
            uiComboDataGridView2.DataGridView.AddCheckBoxColumn("删除", "Iselected",fillWeight:30, readOnly: false);
            uiComboDataGridView2.DataGridView.ReadOnly = false;
            uiComboDataGridView2.ShowFilter = true;
            //点击删除按钮
            uiComboDataGridView2.item.DelItems += () =>
            {
               var del = OscilloscopeControl.modelSaveStrings.FindAll(o=>o.Iselected);
                for (global::System.Int32 j = 0; j < del.Count; j++)
                {
                    var delModel = del[j];
                    if (delModel != null)
                        OscilloscopeControl.modelSaveStrings.Remove(delModel);
                }
                OscilloscopeControl.BindingListmodelSaveStrings.ResetBindings();

            };
            uiComboDataGridView2.BackColor = Color.Red;
            uiComboDataGridView2.ForeColor = Color.Gray;
            var font = new System.Drawing.Font("微软雅黑", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            uiComboDataGridView2.Font = font;
            uiComboDataGridView2.DataGridView.DataSource = OscilloscopeControl.BindingListmodelSaveStrings;
            uIDataGridView = uiComboDataGridView2.DataGridView;
            //  Debug.WriteLine(OscilloscopeControl.BindingListmodelSaveStrings.Count);
            // Debug.WriteLine(OscilloscopeControl.modelSaveStrings.Count);
            UC_BtnAddDelControl userControl3 = new UC_BtnAddDelControl(this, uiComboDataGridView2, OscilloscopeControl.BindingListmodelSaveStrings, OscilloscopeControl.modelSaveStrings, (data) =>
            {
                if (cuurentSelectItem != null)
                {
                    var delModel = OscilloscopeControl.modelSaveStrings.FirstOrDefault(o => o.Name.Equals(cuurentSelectItem.Name));
                    if (delModel != null)
                    {
                        OscilloscopeControl.modelSaveStrings.Remove(delModel);
                        uiComboDataGridView2.Text = ""; //清空文本
                        OscilloscopeControl.BindingListmodelSaveStrings.ResetBindings();
                    }
                }
            })
            { Dock = DockStyle.Top };
            userControl3.AddAction += ((string name, string type, string scale, string add) k) =>
            {
                uiComboDataGridView2.Text = k.name;
                comboBox_type.Text = k.type;
                comboBox_scale.Text = k.scale;
                textBox1.Text = k.add;
                var delModel = OscilloscopeControl.modelSaveStrings.FirstOrDefault(o => o.Name.Equals(uiComboDataGridView2.Text)
                && o.Type.Equals(k.type)
                && o.Scale.Equals(k.scale)
                && o.Address.Equals(k.add)
                );
                if (delModel!=null)
                {
                    cuurentSelectItem = delModel;
                }
                else
                {

                }
                ShowParameter?.Invoke("通道" + i + ":   " + uiComboDataGridView2.Text);
            };
            uiComboDataGridView2.FilterColumnName = "参数名称"; //不设置则全部列过滤
            panel3.Controls.Add(uiComboDataGridView2);
            uiComboDataGridView2.Dock = DockStyle.Top;
            userControl3.Anchor = AnchorStyles.Left;
            panel2.Controls.Add(userControl3);
            //label_Title.Text = $"通道{i}";
            comboBox_type.SelectedIndex = 0;
            comboBox_scale.SelectedIndex = 0;
            comboBox_type.Name = $"comboBoxCH_{i}Type";
            comboBox_scale.Name = $"comboBoxCH_{i}ratio";
            uiComboDataGridView2.Name = $"textBoxCH{i}Addr";
            textBox1.Name = $"textBoxCH{i}Address";
            I = i;
            this.uiComboDataGridView2.ValueChanged += new Sunny.UI.UIComboDataGridView.OnValueChanged(this.uiComboDataGridView2_ValueChanged);

        }



        //当前选中的
     public   ModelSaveString cuurentSelectItem = null;



        private void dgv_SequenceRunState_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            //遍历选中颜色事件
            if (e.RowIndex == -1)
                return;

            Color colorToChange = Color.LightBlue;
            Color colorCurrent = uIDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor;

            if (colorCurrent == Color.LightGreen)
                colorToChange = Color.PaleGreen;
            for (int i = 1; i < 7; i++)
            {
                if (i == 3 || i == 4)
                {
                    continue;
                }
                uIDataGridView.Rows[e.RowIndex].Cells[i].Style.BackColor = colorToChange;
            }
        }


        private void uiComboDataGridView2_ValueChanged(object sender, object value)
        {
            uiComboDataGridView2.Text = "";
            if (value != null && value is DataGridViewSelectedRowCollection)
            {
                DataGridViewSelectedRowCollection collection = (DataGridViewSelectedRowCollection)value;
                foreach (var item in collection)
                {
                    DataGridViewRow row = (DataGridViewRow)item;
                    ModelSaveString selectParaInfo = row.DataBoundItem as ModelSaveString;
                    cuurentSelectItem = selectParaInfo;
                    uiComboDataGridView2.Text += row.Cells["参数名称"].Value.ToString();
                    comboBox_type.Text = selectParaInfo.Type;
                    comboBox_scale.Text = selectParaInfo.Scale;
                    textBox1.Text = selectParaInfo.Address;
                    ShowParameter?.Invoke("通道" + I + ":  " + uiComboDataGridView2.Text);

                }
            }
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        public List<string> GetListContent()
        {
            List<string> content = new List<string>();
            if (/*!string.IsNullOrEmpty(textBox1.Text) &&*/ !string.IsNullOrEmpty(comboBox_type.Text) && !string.IsNullOrEmpty(comboBox_scale.Text))
            {

                content.Add(uiComboDataGridView2.Text);
                content.Add(comboBox_type.Text);
                content.Add(comboBox_scale.Text);
            }
            return content;
        }
        /// <summary>
        /// 获取信息
        /// </summary>
        /// <returns></returns>
        public string GetListContentOrStrings()
        {

            var datsstrings = DuiJsonHelper.ObjectToJson(OscilloscopeControl.modelSaveStrings);
            //List<string> content = new List<string>();
            //{

            //    content.Add(uiComboDataGridView2.Text);
            //    content.Add(comboBox_type.Text);
            //    content.Add(comboBox_scale.Text);
            //}
            return datsstrings;
        }

        public void InitialData(ModelSaveString modelSaveString)
        {
            ChannelSeting channelSeting = SystemSetting.Channels[I];
            ComboBox comboBox_Type = (ComboBox)base.Controls.Find(string.Format("comboBoxCH_{0}Type", I), true)[0];
            ComboBox comboBox_ratio = (ComboBox)base.Controls.Find(string.Format("comboBoxCH_{0}ratio", I), true)[0];
            TextBox comboBoxadd = (TextBox)base.Controls.Find(string.Format("textBoxCH{0}Address", I), true)[0];
            UIComboDataGridView textBox_Addr = (UIComboDataGridView)base.Controls.Find(string.Format("textBoxCH{0}Addr", I), true)[0];
            comboBox_Type.Text = modelSaveString.Type;
            comboBox_ratio.Text = modelSaveString.Scale;
            comboBoxadd.Text = modelSaveString.Address;
            if (modelSaveString != null)
                textBox_Addr.Text = modelSaveString.Name;
            else textBox_Addr.Text = "";
            if (Enum.TryParse(comboBox_ratio.Text, out ENUM_Ratio result_WaveRatio))
            {
                channelSeting.WaveRatio = result_WaveRatio;
            }
            if (Enum.TryParse(comboBox_Type.Text, out ENUM_001 result_SignalType))
            {
                channelSeting.SignalType = (ENUM_001)Enum.Parse(typeof(ENUM_001), (string)comboBox_Type.SelectedItem);
            }
            channelSeting.Address = Convert.ToInt32(modelSaveString.Address, 16);
            cuurentSelectItem = modelSaveString;
            //if (channelSeting.Address != null)
            //{
            //    textBox_Addr.Text = channelSeting.Address.Value.ToString("X4");
            //}
            //else
            //{
            //    textBox_Addr.Text = 0.ToString("X4");
            //}
            //comboBox_Type.SelectedItem = Enum.GetName(typeof(ENUM_001), channelSeting.SignalType);
        }

        private void comboBox_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            //TextBox textBox = (TextBox)base.Controls.Find(string.Format("textBoxCH{0}Addr", key.ToString()), true)[0];
            //if (channelSeting.Address != null)
            //{
            //	textBox.Text = channelSeting.Address.Value.ToString("X4");
            //}
            //else
            //{
            //	textBox.Text = 0.ToString("X4");
            //}
            if (I != 0)
                SystemSetting.Channels[I].SignalType = (ENUM_001)Enum.Parse(typeof(ENUM_001), comboBox.Text);

        }

        private void comboBox_scale_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = sender as ComboBox;
            if (I != 0)
                SystemSetting.Channels[I].WaveRatio = (ENUM_Ratio)Enum.Parse(typeof(ENUM_Ratio), comboBox.Text);
        }
    }
}
